package com.gxa.k12.auth.service.impl;

import com.gxa.k12.auth.entity.UserEntity;
import com.gxa.k12.auth.mapper.UserMapper;
import com.gxa.k12.auth.service.SmsService;
import com.gxa.k12.auth.service.UserService;
import com.gxa.k12.auth.utils.MD5Util;
import com.gxa.k12.auth.utils.SendSms;
import com.gxa.k12.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author ming ming
 * @Date 2021/7/23 15:48
 * @Version 1.0
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class SmsServiceImpl implements SmsService {

    @Autowired
    private  RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    final static  String  LOGIN_SMS="login_sms:";



    @Override
    public String sendLoginSms(String username,String password ) {
        //先验证账号和密码
        Example example = new Example(UserEntity.class);
        Example.Criteria criteria = example.createCriteria();
//        此时密码要进行加密处理
        String encode = MD5Util.encode(password);

        criteria.andEqualTo(username,username).andEqualTo(password,encode);
        List list = userMapper.selectByExample(example);
        if(list==null){
            throw  new BusinessException("用户不存在，或密码错误");
        }
        //通过密码正确后开始获取验证码
        //拿到电话号码后开始发送短信开始校验，调用redis的存储；

        String msgCode = SendSms.getMsgCode();
        //生成的验证码打印在控制台用于作弊获取

        System.out.println("msgCode:"+msgCode);
        //2.服务器存储验证码并设置失效时间为30分钟


        redisTemplate.opsForValue().set(LOGIN_SMS+username,msgCode,30, TimeUnit.MINUTES);


        return null;
    }
}
